package com.mobilesales.android.c2dm.parsers;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.mobilesales.android.R;

public abstract class MessageParserBase {

	private static final int MOBILE_SALES_ID = 5554;

	private Context context;	
	
	public MessageParserBase(Context context) {
		this.context = context;
	}
	
	public MessageParserBase() {}

	public abstract boolean parseMessage(String method, String arg);
	
	protected void invokeMethod(Class<?> cls, String methodName, String arg) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		
		Log.i("invokeMethod", methodName+"("+arg+")");
		Integer id = Integer.parseInt(arg);
		Object[] args = new Object[] { id };
		
		Method method = null;
		for(Method m : cls.getMethods()) {
			if (m.getName().equals(methodName)) {
				method = m;
				break;
			}
		}
		
		if (method==null)
			throw new NoSuchMethodException();
		
		method.invoke(this, args);
	}
	
	public Context getContext() {
		return this.context;
	}
	
	public void setContext(Context context) {
		this.context = context;
	}
	
	public void createNotification(String title, String content, Intent intent) {
		if (this.getContext()!=null) {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager)getContext().getSystemService(ns);
			int icon = R.drawable.basket;
			long when = System.currentTimeMillis();
			
			String appName = this.getContext().getString(R.string.app_name);
			Notification notification = new Notification(icon, appName, when);
		
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.defaults |= Notification.DEFAULT_SOUND;
			Context context = getContext().getApplicationContext();
	
			PendingIntent contentIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	
			notification.setLatestEventInfo(context, title, content, contentIntent);
			mNotificationManager.notify(MOBILE_SALES_ID, notification);
		}
	}
}
